﻿/*
 * @author: wizardc
 */

using System;
using System.Linq;
using System.Net.Sockets;
using Dou.IO;

namespace Dou.Net
{
    /// <summary>
    /// 套接字解包对象的简单实现类
    /// </summary>
    public class SimplePacketParser : IPacketParser
    {
        private Endian _endian;
        private bool _isConnectClosed;

        private byte[] _packet;

        public SimplePacketParser(Endian endian)
        {
            _endian = endian;
            _isConnectClosed = false;
        }

        public bool isConnectClosed => _isConnectClosed;

        public bool ReceiveData(Socket socket)
        {
            // 接收消息头
            byte[] header = new byte[4];
            int headerLen = socket.Receive(header, 0, header.Length, SocketFlags.None);
            // 远程服务端关闭了当前的连接
            if (headerLen <= 0)
            {
                _isConnectClosed = true;
                return false;
            }
            // 得到消息包长度
            if (BitConverter.IsLittleEndian ^ _endian == Endian.LittleEndian)
            {
                header = header.Reverse().ToArray();
            }
            uint bodyLength = BitConverter.ToUInt32(header, 0);
            // 接收消息包
            byte[] body = new byte[bodyLength];
            int bodyLen = socket.Receive(body, 0, body.Length, SocketFlags.None);
            // 远程服务端关闭了当前的连接
            if (bodyLen <= 0)
            {
                _isConnectClosed = true;
                return false;
            }
            // 记录消息包
            _packet = body;
            return true;
        }

        public byte[] GetPacket()
        {
            byte[] packet = _packet;
            _packet = null;
            return packet;
        }
    }
}
